from datetime import datetime, timedelta
from operator import itemgetter
import math

# 计算 x 天的增长率
# current_date 当前天数
# points 基金折线统计
# day 天数
def calculate_seven_day_growth(current_date, points, day):
    fund_list = [item for item in points if item['type'] == 'fund']
    ary = []
    current_date_obj = datetime.strptime(current_date, "%Y-%m-%d")
    timeDataAry = []
    # 下跌次数
    down_count = 0
    up_count = 0
    befor_rate = -100
    while day > 0:
        timeDataAry.append(current_date)
        next_day = current_date_obj - timedelta(days=1)
        current_date = next_day.strftime("%Y-%m-%d")
        current_date_obj = next_day
        day -= 1
    # 获取下跌次数跟上涨次数
    for item in fund_list:
        if item["reportDateTimestamp"] in timeDataAry:
            ary.append(item["rate"])
            if befor_rate == -100:
                befor_rate = item["rate"]
            else:
                if item["rate"] < befor_rate:
                    down_count += 1
                else:
                    up_count += 1
                befor_rate = item["rate"]
    total = 0
    if len(ary) > 0:
        total = ary[-1] - ary[0]
    return  [round(total, 4), down_count, up_count]

# 默认先跌后涨
# firstDown 是否先跌后涨
def up_down_fund_select(funds, current_date, dowmDay, upDay, firstDown=True):
    date_obj = datetime.strptime(current_date, "%Y-%m-%d")
    if firstDown:
        nexData = date_obj - timedelta(days=upDay)
        date = nexData.strftime("%Y-%m-%d")
    else:
        nexData = date_obj - timedelta(days=dowmDay)
        date = nexData.strftime("%Y-%m-%d")
    for fund in funds:
        points = fund["points"]
        day_select = dowmDay
        day_select2 = upDay
        if not firstDown:
            day_select = upDay
            day_select2 = dowmDay
        aryA = calculate_seven_day_growth(date, points, day_select)
        aryB = calculate_seven_day_growth(current_date, points, day_select2)
        lineA = aryA[0]
        lineB = aryB[0]
        fund["lineA"] = lineA
        fund["downACount"] = aryA[1]
        fund["lineB"] = lineB
        fund["upBCount"] = aryB[2]
        fund['difference'] = abs(lineB - lineA)
    ary = []
    for fund in funds:
        if firstDown:
            if fund["lineA"] < 0 and fund["lineB"] > 0 and fund["downACount"] > 15 and fund["upBCount"] > 2:
                ary.append(fund)
        elif fund["lineA"] > 0 and fund["lineB"] < 0:
            ary.append(fund)
    print(len(ary))
    # storyAry = sorted(ary, key=itemgetter('difference'), reverse=True)
    # 计算中间 1/3 的起始和结束索引
    # total_length = len(storyAry)
    # start_index = math.floor(total_length / 3)
    # end_index = math.ceil(2 * total_length / 3)
    # # 取出中间的 1/3 部分
    # middle_third = storyAry[start_index:end_index]
    # middle_third = sorted(middle_third, key=itemgetter('lineB'), reverse=True)
    return ary